<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { CommentApi } from '#/api/wedding/comment';

import { Page, useVbenModal } from '@vben/common-ui';
import { message, Tag, Rate } from 'ant-design-vue';

import { $t } from '#/locales';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { 
  getCommentPage, 
  deleteComment, 
  batchDeleteComments,
  approveComment,
  batchApproveComments,
  exportComments 
} from '#/api/wedding/comment';
import { downloadFileFromBlobPart } from '@vben/utils';

import { useGridColumns, useGridFormSchema } from './data';
import CommentDetail from './modules/comment-detail.vue';

const [CommentDetailModal, commentDetailModalApi] = useVbenModal({
  connectedComponent: CommentDetail,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 查看评论详情 */
function handleView(row: CommentApi.Comment) {
  commentDetailModalApi.setData(row).open();
}

/** 编辑评论 */
function handleEdit(row: CommentApi.Comment) {
  commentDetailModalApi.setData(row).open();
}

/** 删除评论 */
async function handleDelete(row: CommentApi.Comment) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    key: 'action_key_msg',
  });
  try {
    await deleteComment(row.id);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 审核评论 */
async function handleApprove(row: CommentApi.Comment, status: 'approved' | 'rejected') {
  const hideLoading = message.loading({
    content: `正在${status === 'approved' ? '通过' : '拒绝'}评论...`,
    key: 'action_key_msg',
  });
  try {
    await approveComment(row.id, status);
    message.success({
      content: `评论已${status === 'approved' ? '通过' : '拒绝'}`,
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除 */
async function handleBatchDelete() {
  const selectedRows = gridApi.getCheckboxRecords();
  if (selectedRows.length === 0) {
    message.warning('请选择要删除的评论');
    return;
  }

  const hideLoading = message.loading({
    content: `正在删除${selectedRows.length}条评论...`,
    key: 'action_key_msg',
  });
  try {
    await batchDeleteComments(selectedRows.map(row => row.id));
    message.success({
      content: `已删除${selectedRows.length}条评论`,
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量审核 */
async function handleBatchApprove(status: 'approved' | 'rejected') {
  const selectedRows = gridApi.getCheckboxRecords();
  if (selectedRows.length === 0) {
    message.warning('请选择要审核的评论');
    return;
  }

  const hideLoading = message.loading({
    content: `正在${status === 'approved' ? '通过' : '拒绝'}${selectedRows.length}条评论...`,
    key: 'action_key_msg',
  });
  try {
    await batchApproveComments(selectedRows.map(row => row.id), status);
    message.success({
      content: `已${status === 'approved' ? '通过' : '拒绝'}${selectedRows.length}条评论`,
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 导出评论 */
async function handleExport() {
  const data = await exportComments(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '评论数据.xls', source: data });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getCommentPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
    checkboxConfig: {
      enabled: true,
    },
  } as VxeTableGridOptions<CommentApi.Comment>,
});
</script>

<template>
  <Page auto-content-height>
    <CommentDetailModal @success="onRefresh" />

    <Grid table-title="评论管理">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: '批量通过',
              type: 'primary',
              icon: ACTION_ICON.CHECK,
              auth: ['wedding:comment:approve'],
              onClick: () => handleBatchApprove('approved'),
            },
            {
              label: '批量拒绝',
              type: 'default',
              icon: ACTION_ICON.CLOSE,
              auth: ['wedding:comment:approve'],
              onClick: () => handleBatchApprove('rejected'),
            },
            {
              label: '批量删除',
              type: 'default',
              icon: ACTION_ICON.DELETE,
              danger: true,
              auth: ['wedding:comment:delete'],
              onClick: handleBatchDelete,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['wedding:comment:export'],
              onClick: handleExport,
            },
          ]"
        />
      </template>
      <template #rating="{ row }">
        <div class="flex items-center gap-2">
          <Rate :value="row.rating" disabled size="small" />
          <span class="text-xs text-gray-500">({{ row.rating }})</span>
        </div>
      </template>
      <template #status="{ row }">
        <Tag v-if="row.status === 'pending'" color="orange">待审核</Tag>
        <Tag v-else-if="row.status === 'approved'" color="green">已通过</Tag>
        <Tag v-else-if="row.status === 'rejected'" color="red">已拒绝</Tag>
        <Tag v-else-if="row.status === 'deleted'" color="default">已删除</Tag>
        <span v-else>{{ row.status }}</span>
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看详情',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              onClick: handleView.bind(null, row),
            },
            {
              label: '编辑',
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['wedding:comment:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: '通过',
              type: 'link',
              icon: ACTION_ICON.CHECK,
              auth: ['wedding:comment:approve'],
              onClick: handleApprove.bind(null, row, 'approved'),
              show: row.status === 'pending',
            },
            {
              label: '拒绝',
              type: 'link',
              icon: ACTION_ICON.CLOSE,
              auth: ['wedding:comment:approve'],
              onClick: handleApprove.bind(null, row, 'rejected'),
              show: row.status === 'pending',
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['wedding:comment:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
